package com.zsy.petshop_01.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeRefundApplyRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.zsy.petshop_01.common.result.ResponseResult;
import com.zsy.petshop_01.manager.CustomMultipartFile;
import com.zsy.petshop_01.manager.OrderMessageManager;
import com.zsy.petshop_01.manager.QRCodeGeneratorManager;
import com.zsy.petshop_01.model.entity.OrderMessage;
import com.zsy.petshop_01.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.http.HttpRequest;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    AlipayClient alipayClient;
    @Autowired
    OrderMessageManager orderMessageManager;
    @Autowired
    QRCodeGeneratorManager qrCodeGeneratorManager;
    @Autowired
    MinIOService minIOService;

    private String filePath = "C:\\PetShop\\";
    private String outerNet = "https://4f92-240e-476-ffd4-28db-b006-4e40-9986-3e5.ngrok-free.app";

    public ResponseResult<?> createPaymentOrder(String subject, String totalAmount, HttpServletRequest httpRequest) throws AlipayApiException {
        String userId = httpRequest.getHeader("user_id");
        // 生成唯一订单号
        String outTradeNo = UUID.randomUUID().toString().replace("-", "");

        // 创建预支付请求
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(outTradeNo);
        model.setSubject(subject);
        model.setTotalAmount(totalAmount);
        model.setBody(userId);
        model.setTimeoutExpress("30m"); // 支付超时时间
        request.setBizModel(model);
        request.setNotifyUrl(outerNet+"/alipay/notify");
        request.setReturnUrl(outerNet+"/alipay/notify");

        // 执行请求
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            String minIOPath = "";
            String qrCode = response.getQrCode();
            String fileAddress = filePath + UUID.randomUUID() + ".png";
            try {
                qrCodeGeneratorManager.generateQRCodeImage(qrCode, 300, 300, fileAddress);
                File file = new File(fileAddress);
                MultipartFile multipartFile = new CustomMultipartFile(file, file.getName(), file.getName(), "image/png");
                minIOPath = minIOService.uploadFile(multipartFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ResponseResult.success(minIOPath);
        } else {
            throw new AlipayApiException("预支付失败: " + response.getSubMsg());
        }
    }

    @Override
    public ResponseResult<?> updateOrderStatus(String outTradeNo, String productName, String totalAmount, Integer userId) {
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setOrderId(outTradeNo);
        orderMessage.setProductName(productName);
        orderMessage.setPrice(Double.valueOf(totalAmount));
        orderMessage.setUserId(userId);
        orderMessage.setCreateTime((double) System.currentTimeMillis());
        orderMessageManager.insert(orderMessage);
        return ResponseResult.success();
    }

    public ResponseResult<?> refund(String outTradeNo, String totalAmount, String reason) throws AlipayApiException {
        // 创建预支付请求
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        model.setOutTradeNo(outTradeNo);
        model.setRefundAmount(totalAmount);
        model.setOutRequestNo(reason);
        request.setBizModel(model);
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            return ResponseResult.success("支付成功");
        } else {
            return ResponseResult.fail("支付失败:" + response.getMsg());
        }
    }
}
